package com.wu.exception;

import com.wu.base.ApiResponse;
import com.wu.enums.SystemEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @date
 * @remark 异常Advice 全局异常处理
 */
@Slf4j
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 全局异常处理，反正异常返回统一格式
     * 鉴权失败异常
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = UnauthenticatedException.class)
    public ApiResponse unauthenticatedHandler(UnauthenticatedException ex){
        ApiResponse apiResponse = new ApiResponse();
        apiResponse.setCode(ProjectExceptionEnum.INVALID.getCode());
        apiResponse.setMsg(ProjectExceptionEnum.INVALID.getDesc());
        //发生异常进行日志记录，写入数据库或者其他处理，此处省略
        return apiResponse;
    }

    /**
     * 拦截捕捉自定义异常 ProjectBusinessException.class
     * @param pbex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public ApiResponse myExceptionHandler(BusinessException pbex){
        ApiResponse apiResponse = new ApiResponse();
        apiResponse.setCode(pbex.getErrorCode().getCode().toString());
        apiResponse.setMsg(pbex.getErrorCode().getDesc().toString());
        apiResponse.setData(pbex.getMsg());
        //发生异常进行日志记录，写入数据库或者其他处理，此处省略
        return apiResponse;
    }

    @ExceptionHandler(BindException.class)
    public ApiResponse ex(BindException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        return fail(SystemEnum.PARAM_VALIDE_FAIL.getCode(),"参数校验失败：" + getError(bindingResult));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse invalid(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        return fail(SystemEnum.PARAM_VALIDE_FAIL.getCode(), bindingResult.getAllErrors().get(0).getDefaultMessage());
    }


    /**
     * 全局异常处理，反正异常返回统一格式
     * 其他异常
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ApiResponse exceptionHandler(Exception ex){
        log.error("GlobalExceptionHandler-Exception:{ }", ex);
        return fail("", ProjectExceptionEnum.SYSTEM_ERROR.getDesc());
    }
    /**
     * 获取错误信息
     *
     * @param result 错误list
     * @return error
     */
    private String getError(BindingResult result) {
        List<FieldError> list = result.getFieldErrors();
        for (FieldError error : list) {
            return error.getField() + error.getDefaultMessage();
        }
        return null;
    }

    private ApiResponse fail(String code,String msg){
        ApiResponse apiResponse = new ApiResponse();
        if(StringUtils.isBlank(code)){
            apiResponse.setCode(ProjectExceptionEnum.SYSTEM_ERROR.getCode());
        }else {
            apiResponse.setCode(code);
        }
        apiResponse.setMsg(msg);
        return apiResponse;
    }
}
